package com.journaldev.threadpool.jianshu;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 还在使用 SimpleDateFormat？你的项目崩没？
 * 摘自：https://mp.weixin.qq.com/s/WMGdon-ygEfV3xb9EjGv6w
 * <p>
 * Created by chenhs on 2019/4/24.
 **/
public class SimpleDateFormatTest {
    /*
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static String formatDate(Date date) {
        return sdf.format(date);
    }

    public static Date parse(String strDate) throws ParseException {
        return sdf.parse(strDate);
    }*/
    /*
    private static ThreadLocal<DateFormat> sdf = new ThreadLocal<DateFormat>(){
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };*/

    private static ThreadLocal<DateFormat> sdf = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    public static String formatDate(Date date) {
        return sdf.get().format(date);
    }

    public static Date parse(String strDate) throws ParseException {
        return sdf.get().parse(strDate);
    }


    public static void main(String[] args) throws InterruptedException {
        //单线程下执行没毛病
        //System.out.println(sdf.format(new Date()));

        /**
         * 20个线程
         * Exception in thread "pool-1-thread-13" java.lang.NumberFormatException: multiple points
         */
        ExecutorService service = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 20; i++) {
            service.execute(() -> {
                for (int j = 0; j < 10; j++) {
                    try {
                        System.out.println(parse("2019-04-24 16:25:27"));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        //等待上述线程执行完
        service.shutdown();
        service.awaitTermination(1, TimeUnit.DAYS);

    }

}
